<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use think\Request;
use think\facade\Config;
use PHPMailer\PHPMailer\PHPMailer;
use TCPDF;
use Elasticsearch\ClientBuilder;

/*es搜索引擎*/
class Eses extends Base
{   
    private $client;
    private $suoyin='lily';//索引
    private $leixing='lily';//类型
    private $tablename='es';//表名
    private $cname='';
    private $nav=array();
    //private $leixing='cross_fields';//类型

    private $hosts = [
        'elastic:Lily8888@149.28.44.107:9200'  // SSL to IP + Port
    ];

    /*
    setHosts 设置节点信息
    setRetries 重连次数
    */
    public function __construct(){
        parent::__construct();
        $this->client=ClientBuilder::create()->setHosts($this->hosts)->setRetries(0)->build();
    }
    /*准备数据
    步骤: 1 获取 product_middle_table 中Product_Number URL_Product tablename
          2 根据 表名获取对应：列表 数据 分类
          根据分类获取 无限极nav
          3
    */

    /*获取原数据插入es*/
    public function insert_part_number(){
        ini_set('max_execution_time', '0');
        $middle=Db::table('lily_products')->field('part_number,url_product')->select()->toArray();
        
        /*先删除数据*/
        if(!empty($middle)){
            $sql="DELETE FROM ".$this->tablename;
            $a=Db::query($sql);
        }

        $id=1;
        foreach ($middle as $key => $value) {
            $insert = ['id' => $id, 'Product_Number' => $value['part_number'], 'url' => $value['url_product']];
            Db::table($this->tablename)
                ->data($insert)
                ->insert();
           
            $id++;
        }
        //$this->plan_data();
    }
    /*更新图片*/
    public function update_img_dimg(){
        ini_set('max_execution_time', '0');
        $middle=Db::table('lily_products')->field('part_number,img')->select()->toArray();
        foreach ($middle as $key => $value) {
            if(!empty($value['img'])){
                $update="update `".$this->tablename."` set img='".$value['img']."' where Product_Number='".$value['part_number']."'";
                Db::query($update);
            }else{
                $update="update `".$this->tablename."` set img='/static/img/morenlogo.png' where Product_Number='".$value['part_number']."'";
                Db::query($update);
            }
        }
    }
    public function fileds_array_data(){
        ini_set('max_execution_time', '0');
        $d=array();
        $middle=Db::table('lily_products')->field('part_number,class_id')->select();

        /*由于c_id中存在多个数据且不一定是正确的列表页的id*/
        foreach ($middle as $key => $value) {
                $rightdata=Db::table('lily_right_table')->field('fileds')->where('class_id','=',$value['class_id'])->select();
                foreach ($rightdata as $km=>$vm){
                    if(!in_array($vm, $d)){
                        $d[]=$vm;
                    }
                }
        }
       return $d;
    }
    /*更新字段*/
    public function plan_data1(){
        ini_set('max_execution_time', '0');
        $middle=Db::table('lily_products')->field('id,part_number,class_id')->select();

        /*由于c_id中存在多个数据且不一定是正确的列表页的id*/
       
        foreach ($middle as $key => $value) {
            if(!empty($value['class_id'])){
                $neirong_str='';
                $fields_zhi_str='';
                $rightdata=Db::table('lily_right_table')->field('fileds,fileds_alias,seq')->where('class_id','=',$value['class_id'])->order('seq')->select();
                $content=Db::table('lily_products_detail')->field('*')->where('pid','=',$value['id'])->select();
                foreach ($rightdata as $km=>$vm){
                    foreach ($content as $k => $v) {
                        if($v['is_show']&&$vm['fileds']==$v['key']){
                            $neirong_str.=$v['key']." : ".$v['value'].";";
                            $fields_zhi_str.=$v['value'].",";
                        }
                    }
                    if($vm['fileds_alias']){
                        $field_str.= "`".$vm['fileds_alias']."`,";
                    }else{
                        $field_str.= "`".$vm['fileds']."`,";
                    }
                }
                //dump($content);exit;
                $update="update `".$this->tablename."` set neirong='".rtrim($neirong_str,';')."',class_id='".trim($value['class_id'])."',fields='".rtrim(str_replace('`','',$field_str),',')."',fields_zhi='".rtrim($fields_zhi_str,',')."' where Product_Number='".$value['part_number']."'";
                
                Db::query($update);
            }
        }
    }
    /*更新导航面包屑信息*/
    public function plan_data2(){
        ini_set('max_execution_time', '0');
        $middle=Db::table('lily_products')->field('part_number,class_id')->select();

        foreach ($middle as $key => $value) {
                $product=Db::table('lily_products')->field('part_number,class_id')->where('part_number','=',$value['part_number'])->select();
                foreach ($product as $k=>$v){
                    $miambao[]= $v['id'];
                }
                $mian=array();

                foreach ($miambao as $k => $v) {
                   $deal = controller('deal/Index');//调用集中处理模块
                   $mian[$k]=$deal->recursive_up($v,"url,cname");/*调用向上取整*/
                }
                $nav_str='';
                $cname_arr=array();
                foreach ($mian as $k => $vo) {
                    for($i=count($vo);$i>0;$i--){
                      $nav_str.='<a href="'.$vo[$i-1]['url'].'" style="font: 12px/14px arial,helvetica,sans-serif;">'.$vo[$i-1]['cname'].'</a>';
                      if(!in_array($vo[$i-1]['cname'],$cname_arr)){
                         $cname_arr[]=$vo[$i-1]['cname'];
                      }
                    }
                    $nav_str.='</br>';
                }
                
                $cname_str='';
                foreach ($cname_arr as $k => $v) {
                    $cname_str.=$v.",";
                }
                $cname_str=rtrim($cname_str,',');
                $update="update `".$this->tablename."` set nav='".$nav_str."',cname='".$cname_str."' where Product_Number='".$value['part_number']."'";
                Db::query($update);   

        }
    }

    /*更新型号兑换信息*/
    public function update_part_chat(){
        ini_set('max_execution_time', '0');
        $Relationship=Db::table('Chat_Relationship')->whereNotNull('LILY')->select();
        foreach ($Relationship as $key => $value) {
            $Product_Number=$value['LILY'];
            $middle=Db::table('es')->where('Product_Number','=',$Product_Number)->find();
            
            foreach ($value as $k => $vo) {
                if($k!='t_id'&&$k!='id'&&$k!='LILY'){
                    if(!empty($vo)){
                        $check_Product=Db::table('es')->where('Product_Number','=',$vo)->find();
                        if(empty($check_Product)){
                            $insert="insert into `".$this->tablename."` (Product_Number,img,neirong,nav,url,cname,class_id,`fields`,fields_zhi) values ('".$vo."','".$middle['img']."','".str_replace($Product_Number,$vo,$middle['neirong'])."','".$middle['nav']."','".$middle['url']."','".$middle['cname']."','".$middle['class_id']."','".$middle['fields']."','".str_replace($Product_Number,$vo,$middle['fields_zhi'])."')";
                            Db::query($insert);
                        }
                    }
                }
            }
        }

    }
    /*角接触 718 719*/
    public function update_anguar(){
        ini_set('max_execution_time', '0');
        $data=Db::table('Angular')->field('Part_No')->whereNotNull('Part_No')->select();
        foreach ($data as $key => $value) {
            $frist = substr( $value['Part_No'], 0, 1 );
            if($frist=='S'||$frist=='s'){
                $frist3 = substr( $value['Part_No'], 0, 3 );
                if($frist3=='S79'){
                    $p='S719'.substr($value['Part_No'],strripos($value['Part_No'],"S79")+3);
                }
                if($frist3=='S78'){
                    $p='S718'.substr($value['Part_No'],strripos($value['Part_No'],"S78")+3); 
                }
            }else{
                $frist2 = substr( $value['Part_No'], 0, 2 );
                if($frist2=='79'){
                    $p='719'.substr($value['Part_No'],strripos($value['Part_No'],"79")+2);
                }
                if($frist2=='78'){
                    $p='718'.substr($value['Part_No'],strripos($value['Part_No'],"78")+2); 
                }
            }
            
           
            $xiangsi=Db::table('es')->where('Product_Number','=',$p)->find();

            $insert="insert into `".$this->tablename."` (Product_Number,img,neirong,nav,url,cname,class_id,`fields`,fields_zhi) values ('".$value['Part_No']."','".$xiangsi['img']."','".str_replace($xiangsi['Product_Number'],$value['Part_No'],$xiangsi['neirong'])."','".$xiangsi['nav']."','".$xiangsi['url']."','".$xiangsi['cname']."','".$xiangsi['class_id']."','".$xiangsi['fields']."','".str_replace($xiangsi['Product_Number'],$value['Part_No'],$xiangsi['fields_zhi'])."')";
            Db::query($insert);
        }

    }

    /*删除索引*/
    public function delete(){
        $params = ['index' => $this->suoyin];
        $response = $this->client->indices()->delete($params);
       // $this->index();
    }

    /*创建索引*/
    public function index(){
        $fileds_data=$this->fileds_array_data();
         $params['index']='lily';
         $params['body']['settings']=[
            'number_of_shards' => 1,
            'analysis' => [
                'filter' => [
                    'autocomplete_filter' => [
                        'type' => 'edge_ngram',
                        'min_gram' => 1,
                        'max_gram' => 20,
                        "pattern" => " ",
                        "replacement" => "",
                   ],
                   'neirong_filter' => [
                        'type' => 'edge_ngram',
                        'min_gram' => 2,
                        'max_gram' => 20,
                        "pattern" => " ",
                        "replacement" => "",
                    ]
                ],
                'analyzer' => [
                    'autocomplete' => [
                        'type' => 'custom',
                        'tokenizer' => 'keyword',
                        'filter' => ['lowercase', 'autocomplete_filter']
                    ],
                    'neirongs' => [
                        'type' => 'custom',
                        'tokenizer' => 'keyword',
                        'filter' => ['lowercase', 'neirong_filter']
                    ]
                ]   
            ]
        ];

        $a['Product_Number']=['type' => 'text','analyzer' => 'autocomplete','fields'=>['field'=>['type'=>'keyword']]];
        $a['neirong']=['type' => 'text','analyzer' => 'neirongs','fields'=>['field'=>['type'=>'keyword']]];
        $a['cname']=['type' => 'text','analyzer' => 'autocomplete','fields'=>['field'=>['type'=>'keyword']]];
        foreach ($fileds_data as $key => $value) {
            if($value!='Product Number'){
                $a[$value] = ['type' => 'text','analyzer' => 'autocomplete','fields'=>['field'=>['type'=>'keyword']]];
            }
        }
        $params['body']['mappings']['properties']=$a;

        $this->client->indices()->create($params);
        //$this->upindex();

    }
    /*上传数据*/
    public function upindex(){
        ini_set('max_execution_time', '0');
        $sql="select * from ".$this->tablename;
        $data=Db::query($sql);
        $i=1;
        foreach ($data as $key => $value) {
            $params['body'][] = [
                'index' => [
                    '_index' => $this->suoyin,
                    /*'_type' => $this->leixing,*/
                    '_id' => $i,
                ]
            ];
            $a=explode(',',str_replace('_',' ',$value['fields']));
            $b=explode(',',$value['fields_zhi']);

            foreach ($a as $k => $v) {
                if(isset($b[$k])){
                    $value[$v]=$b[$k];
                }else{
                    $value[$v]='';
                }
            }

            $params['body'][] = $value;

            if (count($params['body']) % 1000 == 0) {
                $responses = $this->client->bulk($params);
               
                $params = ['body' => []];
                unset($responses);
            }
            $i++;
        }
        if (!empty($params['body'])) {
            $responses = $this->client->bulk($params);
        }
    }
   


   /*预览*/
    public function get_search(Request $request){
        $post=$request->post();//$post['searinfo']
        $params = [
            'index' => $this->suoyin,
           /* 'type' => $this->leixing,*/
            'body' => [
                "query" => [
                    "multi_match"=>[
                        "query"=>$post['searinfo'],
                        "type"=>'cross_fields',
                        
                        "tie_breaker"=>0.8,
                        "minimum_should_match"=>"90%",
                        
                    ]
                ],
                "track_scores"=>"true",
                "size"=>5,
                "sort"=>[
                    "_score"=> [
                      "order"=>"desc"
                    ]
                ]
            ]
        ];
          
        $results = $this->client->search($params);
        foreach ($results['hits']['hits'] as $key => $value) {
            $dataimg=Db::table('lily_products')->where('part_number','=',$value['_source']['Product_Number'])->find();
            $results['hits']['hits'][$key]['_source']['img']=Config::get('app.images_host').$dataimg['img'];
        }
        return json($results);
    }
    
    public function search_result(Request $request){
        $searinfo=trim(request()->route('search'));
        $post=request()->post();
        $data['seo_title']=str_replace('bearing','',str_replace(' bearing','',str_replace('bearings','',str_replace(" bearings","",$searinfo))))." Bearing Price & Size Chart | Lily Bearing";
        $data['seo_keywords']=str_replace('bearing','',str_replace(' bearing','',str_replace('bearings','',str_replace(" bearings","",$searinfo))))." bearing, ".str_replace('bearing','',str_replace(' bearing','',str_replace('bearings','',str_replace(" bearings","",$searinfo))))." bearing size, ".str_replace('bearing','',str_replace(' bearing','',str_replace('bearings','',str_replace(" bearings","",$searinfo))))." bearing price, ".str_replace('bearing','',str_replace(' bearing','',str_replace('bearings','',str_replace(" bearings","",$searinfo))))." bearing manufacture, ".str_replace('bearing','',str_replace(' bearing','',str_replace('bearings','',str_replace(" bearings","",$searinfo))))." bearing supplier, Lily Bearing";
        $data['seo_desc']="Lily bearing is bearing manufacture and supplier from china.We supply ".str_replace('bearing','',str_replace(' bearing','',str_replace('bearings','',str_replace(" bearings","",$searinfo))))." bearing with any size and great price. Our bearing could be used including but not limited in medical, automotive, food and other industries. Also a formed pre-sales/sales/after-sales program system were used to meet the actual needs.";
        $data['base_data']=$this->base_data;
        if(strpos($searinfo,'/') !== false){ 
          $esi=explode('/', $searinfo);
          if(count($esi)==2){
            if(is_numeric($esi[0])&&is_numeric($esi[1])){
             $searinfo=$esi[0]/$esi[1];
            }
          } 
        }
        if(strpos($searinfo,'mm') !== false){ 
          $searinfo=str_replace('mm',' mm',$searinfo);
        }
        $data['part_number']=$searinfo;

        
        /*$product_middle_table=Db::table('product_middle_table')->field('Product_Number')->where('Product_Number','like',"%".trim($searinfo)."%")->select()->toarray();*/
        
        
        /*查看是否是禁用词*/
        $disable=Db::table('lily_disable')->field('keys')->where('keys','=',trim($searinfo))->find();
        if(empty($disable)){

            $s = [
                'index' => [ $this->suoyin ]
            ];
            $s = $this->client->indices()->getSettings($s);
            if(empty($s['lily'])||!isset($s['lily'])){
                $data['result']="no index";
                $this->assign($data);
                return $this->fetch();
            }
            
            if(empty($post)){
                $params = [
                    'index' => $this->suoyin,
                    /*'type' => $this->leixing,*/
                    'body' => [
                        "query" => [

                            "multi_match"=>[
                                "query"=>$searinfo,
                                "type"=>'cross_fields',
                               /* "fields"=>["Product_Number^1000","neirong^50","cname^100"],*/
                                "tie_breaker"=>0.8,
                                "minimum_should_match"=>"90%",
                                
                            ],
                        ],
                        "track_scores"=>"true",
                        "size"=>100,
                        "from"=>0,
                        "sort"=>[
                            "_score"=> [
                              "order"=>"desc"
                            ]
                        ]
                    ]
                ];
            }else{

                $fields_search=array();
                foreach ($post as $key => $value) {
                    $fields_search=$value;
                }

                $ip=$this->base_data['ip'];
               
                $insert_sql="insert into lily_sear_tongji (`ip`,`type`,`search_content`,`jieguo_status`,`create_time`) values ('".$ip."',3,'".$fields_search.':'.$searinfo."',1,'".date('Y-m-d H:i:s',time())."')";
                Db::query($insert_sql);

                $params = [
                    'index' => $this->suoyin,
                    /*'type' => $this->leixing,*/
                    'body' => [
                        "query" => [

                            "multi_match"=>[
                                "query"=>$searinfo,
                                "type"=>'cross_fields',
                                "fields"=>$fields_search,
                                "tie_breaker"=>0.8,
                                "minimum_should_match"=>"100%",
                                
                            ],
                        ],
                        "track_scores"=>"true",
                        "size"=>100,
                        "from"=>0,
                        "sort"=>[
                            "_score"=> [
                              "order"=>"desc"
                            ]
                        ]
                    ]
                ];
            }
       
            $results = $this->client->search($params);
            $r=$results['hits']['hits'];
            
            
            $related=array();
            if(!empty($r)){
                foreach ($r as $key => $value) {
                    $jiami=md5($value['_source']['right_class_id'].$value['_source']['cname']);
                    $a[$jiami]['title']=$value['_source']['fields'];
                    $a[$jiami]['width']=$value['_source']['fields_width'];
                    $a[$jiami]['nav']=ltrim($value['_source']['nav'],',');
                    $dataimg=Db::table('lily_products')->where('part_number','=',$value['_source']['Product_Number'])->find();
                    $a[$jiami]['img']=Config::get('app.images_host').$dataimg['img'];
                    $a[$jiami]['body'][$value['_source']['Product_Number']]['data']=$value['_source']['fields_zhi'];
                    $a[$jiami]['body'][$value['_source']['Product_Number']]['url']=$value['_source']['url'];
                    
                    foreach ($value['_source'] as $k => $v) {
                        if($k!='id'&&$k!='Product_Number'&&$k!='img'&&$k!='neirong'&&$k!='nav'&&$k!='url'&&$k!='cname'&&$k!='right_class_id'&&$k!='fields'&&$k!='fields_zhi'&&$k!='fields_width'&&$k!='Product Number'&&$k!='Price'){
                            similar_text($v, $searinfo, $percent);
                            
                            if($percent>85){
                                $related[][$k]=$v;
                            }
                            
                             
                        }
                    }
                    
                }
            $data['result']=$a;
            }else{
                $data['result']=null;
            }
            $new_related1 = array();
            $new_related = array();
           
            foreach ($related as $key=>$value) {
               foreach ($value as $k => $v) {
                   $new_related1[]=$k."#数组#".$v;
               }
            }
            $new_re=0;
            $new_related_data=array_count_values($new_related1);
            foreach ($new_related_data as $key=>$value) {
                $new_related[$new_re][explode('#数组#', $key)[0]]=explode('#数组#', $key)[1];
                $new_related[$new_re]['num']=$value;
                $new_re++;
            }

            $data['new_related']=$new_related;
            
            /*if(!array_key_exists($k, $v1)){*/
            
            

            $recommend = [
                'index' => 'recommend',
               /* 'type' => 'lily',*/
                'body' => [
                    "query" => [
                        "more_like_this" => [
                          "fields" => ["words"],
                          "like" => $searinfo,
                          "min_term_freq" => 1,
                          "max_query_terms" => 12,
                        ]
                    ],
                    "size"=>10,
                    "sort"=>[
                        "_score"=> [
                          "order"=>"desc"
                        ]
                    ]
                ]
            ];
            $recommend_result = $this->client->search($recommend);
            $data['recommend_result']=$recommend_result['hits']['hits'];

           
            $page_es_params = [
                    'index' => 'page_es',
                    'body' => [
                        "query" => [

                            "multi_match"=>[
                                "type"=>'cross_fields',
                                "query"=>$searinfo,
                                "fields"=>["h1^1000","title^50","description^5","keywords^3","cont^1"],
                                "tie_breaker"=>0.99,
                                "minimum_should_match"=>"100%",
                                
                            ],
                        ],
                        "track_scores"=>"true",
                        "size"=>5,
                        "from"=>0,
                        "sort"=>[
                            "_score"=> [
                              "order"=>"desc"
                            ]
                        ]
                    ]
                ]; 
           $page_es_params_a = $this->client->search($page_es_params);
           $data['page_result']=$page_es_params_a['hits']['hits'];
           
        }else{
            $data['result']=null;
        }  

        $ip=$this->base_data['ip'];

        if(!empty($data['result'])){
           $insert_sql="insert into lily_sear_tongji (`ip`,`search_content`,`type`,`jieguo_status`,`create_time`) values ('".$ip."','".$searinfo."',2,1,'".date('Y-m-d H:i:s',time())."')";
           Db::query($insert_sql);
        }else{
           $insert_sql="insert into lily_sear_tongji (`ip`,`search_content`,`type`,`jieguo_status`,`create_time`) values ('".$ip."','".$searinfo."',2,2,'".date('Y-m-d H:i:s',time())."')";
           Db::query($insert_sql);
        }
        $insert_sql1="insert into lily_sear_num (`ip`,`search_content`,`create_time`) values ('".$ip."','".$searinfo."','".date('Y-m-d H:i:s',time())."')";
        Db::query($insert_sql1);
        $this->assign($data);
        return $this->fetch();
    }
   

    /*相关词推荐*/
    public function recommend_delete(){
        $params = ['index' => 'recommend'];
        $response = $this->client->indices()->delete($params);
        //$this->recommend();
    }
    public function recommend(){
        $params = [
            'index' => 'recommend',
            'body'  => [
                'settings' => [
                    'number_of_shards' => 1,
                    'analysis' => [
                        'filter' => [
                            'autocomplete_filter' => [
                                'type' => 'edge_ngram',
                                'min_gram' => 1,
                                'max_gram' => 20
                            ]
                        ],
                        'analyzer' => [
                            'autocomplete' => [
                                'type' => 'custom',
                                'tokenizer' => 'standard',
                                'filter' => ['lowercase', 'autocomplete_filter']
                            ]
                        ]
                    ]
                ],
                'mappings' => [
                    
                        'properties' => [
                            'words' => [
                                'type' => 'text',
                                'analyzer' => 'autocomplete'
                            ] 
                        ]
                    
                ]
            ]
        ];
        $this->client->indices()->create($params);
        //$this->uprecommend();
    }
    public function uprecommend(){
        ini_set('max_execution_time', '0');
        $sql="select words from es_open_search";
        $data=Db::query($sql);
        $i=1;
        foreach ($data as $key => $value) {
            $params['body'][] = [
                'index' => [
                    '_index' => 'recommend',
                    /*'_type' => 'lily',*/
                    '_id' => $i,
                ]
            ];
            $params['body'][] = $value;

            if (count($params['body']) % 1000 == 0) {
                $responses = $this->client->bulk($params);
                $params = ['body' => []];
                unset($responses);
            }
            $i++;
        }
        if (!empty($params['body'])) {
            $responses = $this->client->bulk($params);
            
        }
    }

    /*详情页推荐产品*/
    public function detail_product_recommend($p){
        $recommend = [
            'index' => 'lily',
           /* 'type' => 'lily',*/
            'body' => [
                "query" => [
                    "more_like_this" => [
                      "fields" => ["Product_Number"],
                      "like" => $p,
                      "min_term_freq" => 1,
                      "max_query_terms" => 25,
                    ]
                ],
                "size"=>5,
                "sort"=>[
                    "_score"=> [
                      "order"=>"desc"
                    ]
                ]
            ]
        ];
        $recommend_result = $this->client->search($recommend);
        $data=$recommend_result['hits']['hits'];

        return $data;
    }

    /*详情页推荐搜索数据*/
    public function detail_sear_recommend($p,$c){
        $recommend = [
            'index' => 'recommend',
            /*'type' => 'lily',*/
            'body' => [
                "query" => [
                    "more_like_this" => [
                      "fields" => ["words"],
                      "like" => $p." ".$c,
                      "min_term_freq" => 1,
                      "max_query_terms" => 12,
                    ]
                ],
                "size"=>5,
                "sort"=>[
                    "_score"=> [
                      "order"=>"desc"
                    ]
                ]
            ]
        ];
        $recommend_result = $this->client->search($recommend);
        $data=$recommend_result['hits']['hits'];
        return $data;
    }


    /*搜索数据统计接口*/
    public function tongji(Request $request){
       $post=$request->post();//$post['searinfo']
       $ip=$this->base_data['ip'];
       $product_data=Db::table('lily_products')->where('part_number','=',$post['title'])->find();
       
       $insert_sql="insert into lily_sear_tongji (`ip`,`click_url`,`title`,`type`,`search_content`,`create_time`) values ('".$ip."','https://www.lily-bearing.com/products/".$product_data['url_product']."/','".$post['title']."',".$post['type'].",'".$post['search_content']."','".date('Y-m-d H:i:s',time())."')";
        Db::query($insert_sql);
    }

    public function page_es(){
        $params = [
            'index' => 'page_es',
            'body'  => [
                'settings' => [
                    'number_of_shards' => 1,
                    'analysis' => [
                        'filter' => [
                            'autocomplete_filter' => [
                                'type' => 'edge_ngram',
                                'min_gram' => 1,
                                'max_gram' => 20
                            ]
                        ],
                        'analyzer' => [
                            'autocomplete' => [
                                'type' => 'custom',
                                'tokenizer' => 'standard',
                                'filter' => ['lowercase', 'autocomplete_filter']
                            ]
                        ]
                    ]
                ],
                'mappings' => [
                    
                        'properties' => [
                            'keywords' => [
                                'type' => 'text',
                                'analyzer' => 'autocomplete'
                            ],
                            'title' => [
                                'type' => 'text',
                                'analyzer' => 'autocomplete'
                            ],
                            'description' => [
                                'type' => 'text',
                                'analyzer' => 'autocomplete'
                            ],
                            'url' => [
                                'type' => 'text',
                                'analyzer' => 'autocomplete'
                            ],
                            'cont' => [
                                'type' => 'text',
                                'analyzer' => 'autocomplete'
                            ],
                            'h1' => [
                                'type' => 'text',
                                'analyzer' => 'autocomplete'
                            ]
                        ]
                    
                ]
            ]
        ];
        $this->client->indices()->create($params);
        //$this->uprecommend();
    }
   

    public function all_page(){
        $default_lang=config('app.default_lang');
        if($default_lang=='en-us'){
          $list=Db::table('lily_gd_seo')->where("(lang=1 or lang=3) and leixing='list'")->select();
          $dan=Db::table('lily_gd_seo')->where("(lang=1 or lang=3) and leixing='dan'")->select();
        }else{
          $list=Db::table('lily_gd_seo')->where("(lang=1 or lang=2) and leixing='list'")->select();
          $dan=Db::table('lily_gd_seo')->where("(lang=1 or lang=2) and leixing='dan'")->select();
        }
        $uri=config('app.hostname');

        foreach ($list as $key => $value) {
            if($this->url_status($uri.$value['url'])==1){
                $str=file_get_contents($uri.$value['url']);
                $str=explode('<footer>',explode('</nav>', $str)[1])[0];
                if($value['url']!='/'){
                    $h1=explode('</h1>',explode('<h1 style="display:inline-block;">',$str)[1])[0];
                }else{
                    $h1='';
                }
               
                $tags=get_meta_tags($uri.$value['url']);
                if(!isset($tags['keywords'])||empty($tags['keywords'])){
                    $keywords='';
                }else{
                    $keywords=$tags['keywords'];
                }
                if(!isset($tags['description'])||empty($tags['description'])){
                    $description='';
                }else{
                    $description=$tags['description'];
                }
                if(!isset($tags['title'])||empty($tags['title'])){
                    $title='';
                }else{
                    $title=$tags['title'];
                }
                
                $classdata=Db::table('lily_classify_content')->field('des')->where("class_id",'=',$value['class_id'])->find();

                $update="update lily_gd_seo set `keywords`='".$keywords."',`description`='".$description."',`title`='".$title."',`cont`='".addslashes($classdata['des'])."',`h1`='".addslashes($h1)."' where url='".$value['url']."'";
                Db::query($update);
            }
        }

        foreach ($dan as $key => $value) {
            if($this->url_status($uri.$value['url'])==1){
                //$tags=get_meta_tags($uri.$value['url']);
                $str=file_get_contents($uri.$value['url']);
                $str=explode('<footer>',explode('</nav>', $str)[1])[0];
                if($value['url']!='/'){
                    $h1=explode('</h1>',explode('<h1>',$str)[1])[0];
                }else{
                    $h1='';
                }
                
                $cont=$this->replace_html($str);
                $tags=get_meta_tags($uri.$value['url']);
                if(!isset($tags['keywords'])||empty($tags['keywords'])){
                    $keywords='';
                }else{
                    $keywords=$tags['keywords'];
                }
                if(!isset($tags['description'])||empty($tags['description'])){
                    $description='';
                }else{
                    $description=$tags['description'];
                }
                if(!isset($tags['title'])||empty($tags['title'])){
                    $title='';
                }else{
                    $title=$tags['title'];
                }
                $update="update lily_gd_seo set `keywords`='".$keywords."',`description`='".$description."',`title`='".$title."',`cont`='".addslashes($cont)."',`h1`='".addslashes($h1)."' where url='".$value['url']."'";
                Db::query($update);
            }
        }
    }

    public function up_page_es(){
        ini_set('max_execution_time', '0');
        $sql="select url,keywords,description,title,cont,h1 from lily_gd_seo where title!=''";
        $data=Db::query($sql);
        $i=1;
        foreach ($data as $key => $value) {
            $params['body'][] = [
                'index' => [
                    '_index' => 'page_es',
                    /*'_type' => 'lily',*/
                    '_id' => $i,
                ]
            ];
            $params['body'][] = $value;

            if (count($params['body']) % 1000 == 0) {
                $responses = $this->client->bulk($params);
                $params = ['body' => []];
                unset($responses);
            }
            $i++;
        }
        if (!empty($params['body'])) {
            $responses = $this->client->bulk($params);
            
        }
    }
    

    public function replace_html($document){
        $search = array ("'<script[^>]*?>.*?</script>'si", "'<style[^>]*?>.*?</style>'si", "'<[/!]*?[^<>]*?>'si", "'<!--[/!]*?[^<>]*?>'si","'([rn])[s]+'", "'&(quot|#34);'i","'&(amp|#38);'i","'&(lt|#60);'i","'&(gt|#62);'i","'&(nbsp|#160);'i","'&(iexcl|#161);'i","'&(cent|#162);'i","'&(pound|#163);'i","'&(copy|#169);'i");
 
        $replace = array ("","","","","\1","\"","&","<",">"," ",chr(161),chr(162),chr(163),chr(169));
        $m='\\1';
        $out = preg_replace($search, $replace, $document,-1);
        $out = preg_replace_callback("'&#(d+);'", function($m){
           return chr($m[1]);
        }, $out,-1);
        return $out;
    }
   


    /*查看url是否正常访问*/
    public function url_status($url){
        $array = get_headers($url,1);

        if(preg_match('/200/',$array[0])){
           return 1;
        }else{
            return 0;
        }
    }



}